package com.sunfeng.n6;

import java.math.BigDecimal;

/**
 * 安全实现-使用锁
 * @author sunfeng
 * @date 2021/04/14 13:37
 **/
public class DecimalAccountSafeLock implements  DecimalAccount{

    private final Object lock = new Object();

    BigDecimal balance;

    public DecimalAccountSafeLock(BigDecimal balance) {
        this.balance = balance;
    }

    @Override
    public synchronized   BigDecimal getBalance() {
        return balance;
    }

    @Override
    public synchronized void withdraw(BigDecimal amount) {
            synchronized (lock){
                BigDecimal balance = this.getBalance();
                this.balance = balance.subtract(amount);
            }
    }
}
